package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 均先生
 * Date: 2024-02-23
 * Time: 22:52
 */
@Slf4j
@RestController
@RequestMapping("/music")
public class MusicController {
    @Value("${music.local.path}")
    private String SAVE_PATH;

    @Autowired
    private MusicMapper musicMapper;

    @Autowired
    private LoveMusicMapper loveMusicMapper;
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insert(@RequestParam String singer,
                                               @RequestParam("filename") MultipartFile file,
                                               HttpServletRequest request,HttpServletResponse response) throws IOException {
        //1.检查是否登录
        HttpSession session = request.getSession(false);
        if (!isLogin(request)) {
            return new ResponseBodyMessage<>(-1,"请先登录",false);
        }

        //2.上传到了服务器
        String fileNameAndType = file.getOriginalFilename();
        System.out.println("fileNameAndType --->>>>>>>>>>>>> " + fileNameAndType);

        int dot = fileNameAndType.lastIndexOf("-");
        String title = fileNameAndType.substring(0,dot);
        if (title.length() > 50) {
            title = title.substring(0,50);
        }

        String path = SAVE_PATH + title + ".mp3";

        File dest = new File(path);
        System.out.println("dest="+dest.getPath());

        // 判断上传文件是否为 MP3 文件
        if (!isMP3File(file)) {
            return new ResponseBodyMessage<>(-1, "请上传 MP3 文件", false);
        }



        // return new ResponseBodyMessage<>(-1,"上传失败",false);

        //TODO:上传数据库前查看数据库内是否有此内容[判断依据:文件名]


        Music selectMusic = musicMapper.select(title);
        if (selectMusic == null) {
            //进行数据库的上传
            //1.准备需要的数据
            //2.调用insert


            User user =(User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
            int userid = user.getId();

            //播放音乐 -> http请求 存入时没有后缀.mp3
            String url = "/music/get?path=" + title;

            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            String time = sf.format(new Date());

            try {
                int ret = 0;
                ret = musicMapper.insert(title,singer,time,url,userid);

                if (ret == 1){

                    if (!dest.exists()) {
                        dest.mkdir();
                    }
                    response.sendRedirect("/list.html");
                    file.transferTo(dest);//文件上传服务器

                    System.out.println("服务器上传成功");
                    return new ResponseBodyMessage<>(1,"数据库上传成功",true);
                }

                else return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
            }catch (BindingException e) {
                dest.delete();//因为先在服务器中创建后在数据库中创建,因此数据库中上传失败不影响服务器中上床,所以删除服务器中的文件
                return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
            }


        }else {
            System.out.println("已上传!");
            return new ResponseBodyMessage<>(-1,"数据库内已有该内容!",false);
        }


    }

    /**
     * 播放音乐是,路径为/music/get?path=xxx.mp3
     * @param path
     * @return
     */
    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path) {
        File file = new File(SAVE_PATH+"/"+path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if (a == null) return ResponseEntity.badRequest().build();
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除单个音乐
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id,HttpServletRequest request) {
        //1.先登录
        if (!isLogin(request)) return new ResponseBodyMessage<>(-1,"请先登录",false);

        //2.先检查音乐是否存在
        int musicId = Integer.parseInt(id);
        Music music = musicMapper.findMusicById(musicId);
        if (music == null) {
            log.error("没有你要删除的音乐");
            File file = new File(SAVE_PATH + "/" + music.getTitle() + ".mp3");
            if (file.delete()) return new ResponseBodyMessage<>(1,"服务器中音乐删除成功",true);
            return new ResponseBodyMessage<>(-1,"没有你要删除的音乐",false);
        }else {//2.存在就进行删除
            //2_1.删除数据库文件
            int ret = musicMapper.deleteMusicById(musicId);
            if (ret == 1) {
                //2_2.删除服务器文件
                String filename = music.getTitle();
                File file = new File(SAVE_PATH + "/" +filename + ".mp3");
                System.out.println("当前的路径:" + file.getPath());
                if (file.delete()) {
                    //同时删除lovemusic上的数据
                    if (loveMusicMapper.deleteLoveMusicByMusicId(musicId) == 1) {
                        log.info("同时删除了收藏夹上的数据");
                    }
                    return new ResponseBodyMessage<>(1,"服务器中音乐删除成功",true);
                }else {
                    return new ResponseBodyMessage<>(-1,"服务器上没有该音乐",false);
                }
            }else {
                return new ResponseBodyMessage<>(-1,"数据库上的音乐没有删除成功",false);
            }
        }
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping("deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer> id,HttpServletRequest request) {
        //1.检查登录
        if (!isLogin(request)) return new ResponseBodyMessage<>(-1,"请先登录",false);

        int sum = 0;
        for (int i = 0; i < id.size(); i++) {
            Music music = musicMapper.findMusicById(id.get(i));
            if (music == null) {
                log.error("没有你要删除的音乐");
                return new ResponseBodyMessage<>(-1,"没有你要删除的音乐",false);
            }
            int ret = musicMapper.deleteMusicById(id.get(i));
            if (ret == 1) {
                String filename = music.getTitle();
                File file = new File(SAVE_PATH + "/" +filename + ".mp3");
                System.out.println("当前的路径:" + file.getPath());
                if (file.delete()) {
                    //同时删除lovemusic上的数据
                    if (loveMusicMapper.deleteLoveMusicByMusicId(id.get(i)) == 1) {
                        log.info("同时删除了收藏夹上的数据");
                    }
                    sum += ret;
                    /*return new ResponseBodyMessage<>(1,"服务器中音乐删除成功",true);*/
                }else {
                    return new ResponseBodyMessage<>(-1,"数据库上的音乐删除失败",false);
                }
            }
        }
        if (sum == id.size()) {
            System.out.println("整体删除成功");
            return new ResponseBodyMessage<>(1,"音乐删除成功",true);
        }else {
            System.out.println("整体删除失败");
            return new ResponseBodyMessage<>(-1,"音乐删除失败",false);
        }
    }

    @RequestMapping("/findMusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName
            ,HttpServletRequest request) {
        //1.登录检查
        if (!isLogin(request)) return new ResponseBodyMessage<>(-1,"请先登录",null);

        List<Music> musicList = null;
        if (musicName != null) {
            musicList = musicMapper.findMusicByName(musicName);
        }else {
            musicList = musicMapper.findMusic();
        }
        return new ResponseBodyMessage<>(1,"查询到了所有的音乐",musicList);
    }

    /**
     * 判断文件是否为 MP3 文件
     * @param file 上传的文件
     * @return 如果文件是 MP3 文件返回 true，否则返回 false
     */
    private boolean isMP3File(MultipartFile file) throws IOException {
        byte[] fileBytes = file.getBytes();
        if (fileBytes.length < 3) {
            return false;
        }
        // 检查文件头部是否符合 MP3 文件格式
        return fileBytes[0] == (byte) 0x49 && fileBytes[1] == (byte) 0x44 && fileBytes[2] == (byte) 0x33; // 对于 MP3 文件，前三个字节通常是“ID3”
    }

    protected static boolean isLogin(HttpServletRequest request) {
        //1.检查是否登录
        HttpSession session = request.getSession(false);//没有session不创建
        if (session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            System.out.println("没有登录");
            return false;
        }
        return true;
    }
}
